package com.sto.stoapp.thread;

import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.DownLoadDao;
import com.sto.stoapp.download.DownFactory;
import com.sto.stoapp.download.EnunDownLoad;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.http.URLActions;
import com.sto.stoapp.http.request.download.DownLoadRequest;
import com.sto.stoapp.http.response.download.DownLoadResponse;
import com.sto.stoapp.http.response.download.info.BaseInfo;
import com.sto.stoapp.http.response.download.info.DatadictInfo;
import com.sto.stoapp.http.response.download.info.EffectiveTypeInfo;
import com.sto.stoapp.http.response.download.info.EmpInfo;
import com.sto.stoapp.http.response.download.info.FrequencyInfo;
import com.sto.stoapp.http.response.download.info.GoodsTypeInfo;
import com.sto.stoapp.http.response.download.info.IssueInfo;
import com.sto.stoapp.http.response.download.info.NextStopInfo;
import com.sto.stoapp.http.response.download.info.OderReturnReasonInfo;
import com.sto.stoapp.http.response.download.info.OrgInfo;
import com.sto.stoapp.http.response.download.info.OrgRuleInfo;
import com.sto.stoapp.http.response.download.info.RegionInfo;
import com.sto.stoapp.http.response.download.info.RouteInfo;
import com.sto.stoapp.http.response.download.info.ScanRuleInfo;
import com.sto.stoapp.http.response.download.info.UserInfo;
import com.sto.stoapp.http.response.download.info.UserInfoInfo;
import com.sto.stoapp.http.response.download.info.UserRuleInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.scan.ScanRuleManager;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.util.Helper;

public class BasicDataDLThread extends BaseThread implements MessageType {
	Context context;
	Handler handler;
	EnunDownLoad downType;
	DownLoadDao dao;
	int handleDownType;

	public BasicDataDLThread(Context context, Handler handler,
			EnunDownLoad downType, int handleDownType) {
		super(context);
		this.context = context;
		this.handler = handler;
		this.downType = downType;
		this.handleDownType = handleDownType;

		dao = DownFactory.getDownDao(downType, context);
		if (dao == null) {
			ExceptionLog.writeLog("BasicDataDLThread", "dao=null EnunDownLoad:"
					+ downType.getTableName());

		}

	}

	@Override
	public void run() {
		super.run();
		try {

			String MaxVersion = dao.getMaxVersion();
			DownLoadRequest request = new DownLoadRequest(context,
					downType.getDownType(), MaxVersion);
			HttpManager mgr = new HttpManager();
			String json = request.buildToRequestString();
			String response = mgr.doPostClient(json, StoFilePreference
					.getInstance(context).getServerIp()
					+ URLActions.BASIC_DOWN_ACTION);
			delData(response);
		} catch (Exception e) {
			StoDownServer.removeDownType(handleDownType);
			e.printStackTrace();
			ExceptionLog.writeLog("BasicDataDLThread", e.toString());
			showMsgFaile();
		} finally {
			StoDownServer.removeDownType(handleDownType);
		}
	}

	private void delData(String responseStr) {

		// if (downType == EnunDownLoad.NEXT_STOP_TABLE) {
		// System.out.println(responseStr);
		// }
		// if (downType == EnunDownLoad.ISSUE_TABLE) {
		// System.out.println(responseStr);
		// }
		handleData(responseStr);

	}

	private void handleData(String responseStr) {

		DownLoadResponse response = null;
		try {
			response = getDownLoadResponse(responseStr, downType);
		} catch (JsonSyntaxException e) {
			showResult("数据解析失败");
			e.printStackTrace();
			ExceptionLog.writeLog("BasicDataDLThread", e.toString());
		}

		if (response == null) {
			ExceptionLog.writeLog("BasicDataDLThread", "response 收到错误信息:"
					+ responseStr);
			Log.e("BasicDataDLThread", "收到错误信息:" + responseStr);
			showMsgFaile();

			return;
		}
		List<BaseInfo> list = response.downParam;
		if (list == null || list.size() == 0) {
			if ("001".equals(response.respCode)) {
				showResult(response.resMessage);
			} else {
				showResult(downType.getTableName() + "表下载到0条");
			}
			return;
		}

		if (dao == null) {
			Log.e("BasicDataDLThread ", "dao==null:");
			return;
		}
		dao.insertOrReplace(list);
		dao.deleteDataByStatus("INVALID");
		showMsgSuccess();
		/**
		 * 刷新条码类型
		 */
		if (downType == EnunDownLoad.SCAN_RULE_TABLE) {
			ScanRuleManager.getInstance(context).refreshFromDB();
		}

	}

	private DownLoadResponse getDownLoadResponse(String responseStr,
			EnunDownLoad downType) {
		Gson gson = new Gson();

		if (downType == EnunDownLoad.ISSUE_TABLE)

			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<IssueInfo>>() {
					}.getType());
		// case OFFLINE_LOGIN:
		// response = gson.fromJson(responseStr,
		// new TypeToken<DownLoadResponse<UserInfo>>() {
		// }.getType());
		//
		// // TODO: OffLineManager.insert
		// break;
		else if (downType == EnunDownLoad.REGION_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<RegionInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.ORDER_RETURN_REASON_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<OderReturnReasonInfo>>() {
					}.getType());

		else if (downType == EnunDownLoad.ORG_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<OrgInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.NEXT_STOP_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<NextStopInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.USER_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<UserInfo>>() {
					}.getType());
		/*
		 * 路由下载 RouteInfo
		 */
		else if (downType == EnunDownLoad.ROUTE_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<RouteInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.EMP_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<EmpInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.USER_INFO_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<UserInfoInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.USER_RULE_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<UserRuleInfo>>() {
					}.getType());

		else if (downType == EnunDownLoad.ORG_RULE_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<OrgRuleInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.DATADICT_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<DatadictInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.GOODS_TYPE_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<GoodsTypeInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.EFFECTIVE_TYPE_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<EffectiveTypeInfo>>() {
					}.getType());
		else if (downType == EnunDownLoad.FREQUENCY_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<FrequencyInfo>>() {
					}.getType());

		else if (downType == EnunDownLoad.SCAN_RULE_TABLE)
			return gson.fromJson(responseStr,
					new TypeToken<DownLoadResponse<ScanRuleInfo>>() {
					}.getType());
		else
			return null;
	}

	private void showResult(final String text) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				Helper.showToast(context, text);

			}
		});
	}

	private void showMsgFaile() {
		showResult(downType.getTableName() + "表下载失败");
	}

	private void showMsgSuccess() {
		showResult(downType.getTableName() + "表下载成功");
	}
}
